<!--
 * @Author: zl
 * @Date: 2021-02-05 14:52:13
 * @LastEditTime: 2021-11-30 18:50:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue3-element-admin\src\views\layoutpages\system\Users.vue
-->
<template>
    <div class="ve_container">
        <!-- 搜索 -->
        <el-form ref="queryForm" :inline="true" :model="params">
            <el-form-item label="角色" prop="role">
                <el-select clearable v-model="roleId" placeholder="请选择">
                    <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    @click="onSubmit(params, getDataList)"
                >
                    {{ menus.search.name }}
                </el-button>
                <!--                <el-button @click="resetForm(queryForm, params, getDataList)">-->
                <!--                    重置-->
                <!--                </el-button>-->
            </el-form-item>
        </el-form>

        <!-- 列表 -->
        <ve-table
            :table="{
                data: tableData,
            }"
            :pagination="{
                onSizeChange: (val) =>
                    handleSizeChange(val, params, getDataList),
                onCurrentChange: (val) =>
                    handleCurrentChange(val, params, getDataList),
                currentPage: page,
                pageSize: limit,
                total: total,
            }"
        >
            <template #tool_bar>
                <el-button
                    v-permission="['add']"
                    size="mini"
                    type="primary"
                    @click="handleEdit(menus.add.name)"
                >
                    {{ menus.add.name }}
                </el-button>
            </template>
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column prop="loginName" label="账号"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="role" label="角色">
                <template v-slot="{ row }">
                    <el-tag>
                        {{
                            (row.roleId || row.roleId == 0) &&
                            roleList.filter((item) => item.id == row.roleId)[0]
                                .roleName
                        }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template v-slot="{ row }">
                    <el-switch
                        :loading="row.load ? true : false"
                        v-model="row.status"
                        :active-value="1"
                        :inactive-value="0"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        @change="(val) => handelSwitch(val, row)"
                    >
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="350px">
                <template v-slot:default="{ row }">
                    <el-button
                        v-permission="['edit']"
                        @click.prevent="handleEdit(menus.edit.name, row)"
                        type="primary"
                        size="mini"
                    >
                        {{ menus.edit.name }}
                    </el-button>
                    <el-button
                        v-permission="['del']"
                        @click.prevent="handleDel(row.id)"
                        type="danger"
                        size="mini"
                    >
                        {{ menus.del.name }}
                    </el-button>
                    <el-button
                        v-permission="['reset']"
                        @click.prevent="restPassword(row.id)"
                        type="primary"
                        size="mini"
                    >
                        {{ menus.reset.name }}
                    </el-button>
                    <el-button
                        v-permission="['ewm']"
                        @click.prevent="showEwm(row.id)"
                        type="primary"
                        size="mini"
                    >
                        {{ menus.ewm.name }}
                    </el-button>
                </template>
            </el-table-column>
        </ve-table>

        <!-- 编辑组件 -->
        <users-edit
            v-if="showDialog"
            :rowData="rowData"
            :title="dialogTitle"
            :showDialog="showDialog"
            @closeDialog="handelDialog($event)"
        />

        <el-dialog title="二维码信息" width="30%" v-model="dialogFileVisible">
            <el-form ref="queryForm" :inline="true">
                <el-form-item
                    label="文字显示"
                    prop="name"
                    style="display: none"
                >
                    <el-input
                        clearable
                        v-model="ewmText"
                        placeholder="请输入"
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="createNewEwm(ewmText)">
                        生成
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="downloadEwm()">
                        下载
                    </el-button>
                </el-form-item>
            </el-form>
            <img class="ewmImage" :src="ewmUrl" />
        </el-dialog>
    </div>
</template>
<script>
export default {
    data: () => ({
        description: "用户信息查询与设置",
        menus: {
            search: { name: "查询" },
            add: { name: "添加" },
            edit: { name: "编辑" },
            del: { name: "删除" },
            reset: { name: "重置密码" },
            ewm: { name: "生成填报码" },
        },
    }),
};
</script>

<script setup>
import UsersEdit from "./components/UsersEdit";
import { reactive, toRefs, ref, onMounted, getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
//?导入公共查询方法
import {
    onSubmit,
    handleSizeChange,
    handleCurrentChange,
} from "@/views/layoutpages/common";
import { base64ToBlob } from "@/utils";

const { proxy } = getCurrentInstance();
const route = useRoute();
const rowData = ref(null);
const dialogTitle = ref("");
const showDialog = ref(false);
const queryForm = ref(null);
const tableData = ref([]);
const dialogFileVisible = ref(false);
const ewmText = ref("");
const ewmUrl = ref("");
const ewmUserId = ref("");

const params = reactive({
    roleId: isNaN(route.query.id * 1) ? "" : route.query.id * 1,
    pageSize: 10,
    page: 1,
    total: 0,
    userId: sessionStorage.getItem("unameid"),
});
// eslint-disable-next-line no-unused-vars
const { roleId, pageSize, page, total } = toRefs(params);

const roleList = ref([]);

/**
 * @description:添加or编辑事件
 * @param {*}
 * @return {*}
 */
const handleEdit = (title, row = null) => {
    showDialog.value = true;
    dialogTitle.value = title;
    rowData.value = row;
};
/**
 * @description: 获取角色列表
 * @param {*}
 * @return {*}
 */
const getRoleList = async () => {
    const { code, data } = await VE_API.system.roleList();
    if (code == "00") {
        roleList.value = data;
    }
};
/**
 * @description: dialog事件
 * @param {*}
 * @return {*}
 */
const handelDialog = (e) => {
    showDialog.value = e;
    getDataList();
};
/**
 * 显示二维码页面
 */
const showEwm = async (id) => {
    ewmUserId.value = id;
    ewmUrl.value = "";
    dialogFileVisible.value = true;
    const { code, data } = await VE_API.system.userEwm({
        userId: id,
        text: ewmText.value,
    });
    ewmUrl.value = data;
};
/**
 * 重新生成二维码
 */
const createNewEwm = (text) => {
    ewmText.value = text;
    showEwm(ewmUserId.value);
};
/**
 * 下载二维码图片
 */
const downloadEwm = () => {
    let fileName = ewmText.value == "" ? "二维码.png" : ewmText.value + ".png";
    let blob = base64ToBlob(ewmUrl.value);
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", fileName);
    a.setAttribute("target", "_blank");
    let clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
};

/**
 * @description:用户状态切换
 * @param {*}
 * @return {*}
 */
const handelSwitch = async (val, row) => {
    if (row.id == undefined) return;
    row.load = 1;
    const { code } = await VE_API.system.userStatus(
        {
            id: row.id,
            status: val,
        },
        { Global: false }
    );
    setTimeout(() => {
        row.load = 0;
        if (code != "00") {
            row.status = val == 1 ? 0 : 1;
        }
    }, 500);
};
/**删除行数据
 * @description:
 * @param {*}
 * @return {*}
 */
const handleDel = (id) => {
    proxy
        .$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error",
        })
        .then(async () => {
            const { code } = await VE_API.system.userDel([id]);
            if (code == "00") {
                getDataList();
            }
        })
        .catch(() => {
            proxy.$message({
                type: "info",
                message: "已取消删除",
            });
        });
};
const restPassword = async (id) => {
    proxy
        .$confirm("是否重置密码？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(async () => {
            let editPassword = {
                id: id,
                password: "yzp123456",
            };
            let res = await VE_API.system.userPassword(editPassword);
            if (res.code == "00") {
                proxy
                    .$alert("默认密码为：【yzp123456】", "重置密码成功", {
                        confirmButtonText: "确定",
                        type: "success",
                    })
                    .then(async () => {});
            } else {
                proxy.$message({
                    type: "error",
                    message: "重置密码失败，请联系管理员",
                });
            }
        })
        .catch(() => {
            proxy.$message({
                type: "info",
                message: "已取消删除",
            });
        });
};

/**
 * @description: 获取列表数据
 * @param {*}
 * @return {*}
 */
const getDataList = async () => {
    const { code, data } = await VE_API.system.userList(params);
    if (code == "00") {
        const { pageSize, pageNum, total, list } = data;
        params.pageSize = pageSize;
        params.page = pageNum;
        params.total = total;
        tableData.value = list;
    }
};
onMounted(async () => {
    await getRoleList();
    await getDataList();
    // maxHeight(pagination, queryForm, toolBar, ve_max_height);
});
</script>

<style lang="scss" scoped>
.ewmImage {
    width: 100%;
}
</style>
